package com.gwthtml.samples.chatdemo.server;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.gwthtml.samples.chatdemo.client.ChatMessage;
import com.gwthtml.samples.chatdemo.client.ChatService;

public class ChatServiceImpl extends RemoteServiceServlet implements ChatService {

	private static List<ChatMessage> messages = new ArrayList<ChatMessage>();	
	
	public ChatMessage[] sendMessage(ChatMessage toSend, int latestSeq) {
		synchronized (messages) {
			if (toSend != null) {
				if (toSend.getMessage().trim().length() != 0 &&
						toSend.getNick().trim().length() != 0) {
					messages.add(toSend);
					toSend.setSequenceNum(messages.indexOf(toSend));
				}
			}
			if (latestSeq < messages.size() -1) {
				List<ChatMessage> subl = messages.subList(latestSeq + 1, messages.size());
				ChatMessage[] result = new ChatMessage[subl.size()];
				int i = 0;
				for (ChatMessage m : subl) {
					result[i++] = m;
				}
				return result;
			}
		}
		return null;
	}
}
